package com.ys.service.business.impl;

import com.alibaba.fastjson.JSON;
import com.ys.entity.business.TpHolidaySet;
import com.ys.entity.business.TpShopRegisterPhaseRecord;
import com.ys.entity.business.TpShopRegisterPhaseSet;
import com.ys.entity.hr.ThrOperateCompanyApply;
import com.ys.entity.sys.TsUserChange;
import com.ys.entity.sys.TsUserInfo;
import com.ys.enume.finance.TcwUserPointRunningEnum;
import com.ys.mapper.business.DiySqlMapper;
import com.ys.mapper.business.TpShopRegisterPhaseRecordMapper;
import com.ys.service.business.TpShopRegisterPhaseRecordService;
import com.ys.service.finance.TcwAccountCountForUserService;
import com.ys.service.finance.TcwAccountCountForUserService.ChangePointDto;
import com.ys.service.finance.TcwAccountCountForUserService.ChangePointFrozenDto;
import com.ys.util.shiro.ShiroUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Service("tpShopRegisterPhaseRecordService")
public class TpShopRegisterPhaseRecordServiceImpl implements TpShopRegisterPhaseRecordService {


	@Autowired
	private TpShopRegisterPhaseRecordMapper tpShopRegisterPhaseRecordMapper;

	@Autowired
	private DiySqlMapper diySqlMapper;
    @Autowired
    private TcwAccountCountForUserService tcwAccountCountForUserService;

	/**
	 * 新增
	 * @param params
	 * @return
	 */
	@Override
	public int add(Map<String, Object> params) {
		int result = 0;
		TpShopRegisterPhaseRecord entity = JSON.parseObject(JSON.toJSONString(params), TpShopRegisterPhaseRecord.class);
		//获取当前时间
		Date nowDate = new Date();
		//获取第一条的设置信息
		TpShopRegisterPhaseSet setInfo = new TpShopRegisterPhaseSet().setPhaseType(0).setPhaseNum(1).queryFirst();
		if(setInfo!=null){
			//信息填入
			entity = addEntitySet(entity.getOperateCompanyId(),nowDate,setInfo);
			result = tpShopRegisterPhaseRecordMapper.insert(entity);
		}
		return result;
	}

	/**
	 * 批量新增
	 * @return
	 */
	@Override
	public int addList(List<String> strList) {
		int addResult = 0;
		//获取当前时间
		Date nowDate = new Date();
		//获取所有的设置信息
		List<TpShopRegisterPhaseSet> setList = new TpShopRegisterPhaseSet().queryList();

		if(setList!=null && setList.size()>0){
			//获取第一条的设置信息
			List<TpShopRegisterPhaseSet> setInfo = setList.stream().filter(item -> item.getPhaseType()==0 && item.getPhaseNum()==1).collect(Collectors.toList());
			for(String idStr : strList){
				addRecord(setInfo,Long.parseLong(idStr),nowDate,setList);
			}
			/*
			List<TpShopRegisterPhaseRecord> entityList = new ArrayList<>();
			for(String idStr : strList){
				TpShopRegisterPhaseRecord entity = addEntitySet(Long.parseLong(idStr),nowDate,setInfo);
				entityList.add(entity);
			}
			addResult = diySqlMapper.insertBatchTpShopRegisterPhaseRecord(entityList);

			 */
			addResult = 1;
		}
		return addResult;
	}

	/**
	 * 完成任务
	 * @param params
	 * @return
	 */
	@Override
	@Transactional
	public int edit(Map<String, Object> params, List<TpShopRegisterPhaseSet> setList) throws Exception {

		//修改
		TpShopRegisterPhaseRecord entity = JSON.parseObject(JSON.toJSONString(params), TpShopRegisterPhaseRecord.class);

		//获取记录表信息
		TpShopRegisterPhaseRecord recordInfo = new TpShopRegisterPhaseRecord()
				.setId(entity.getId())
				.queryFirst();

		//获取当前记录id的设置信息
		List<TpShopRegisterPhaseSet> infoList = setList.stream().filter(item -> item.getId().equals(recordInfo.getSetId())).collect(Collectors.toList());

		int res = 0;
		//点击完成时，判断阶段设置是否已经被删除的情况
		if(infoList!=null && infoList.size()>0){
			TpShopRegisterPhaseSet thisSetInfo = infoList.get(0);

			//获取当前时间
			Date nowDate = new Date();
			//填入需要修改的数据
			entity = editEntitySet(entity,recordInfo,thisSetInfo,nowDate);

			//获取当前任务的 流程类型 0主流程,1分支流程 setList
			int setPhaseType = thisSetInfo.getPhaseType();
			if(setPhaseType == 0){//如果是主流程
				//新增下一阶段的跟踪信息
				int isShow = addNextRecord(entity,setList,nowDate);
				entity.setIsShow(isShow);
			}else {//如果是分支流程
				//获取跟踪单当前公司所有数据
				List<TpShopRegisterPhaseRecord> recordInfoByCompanyIdList = new TpShopRegisterPhaseRecord()
						.where("A.OperateCompanyId = "+ recordInfo.getOperateCompanyId())
						.queryList();

				int isShow = addParentsRecord(recordInfo.getOperateCompanyId(),recordInfoByCompanyIdList,setList,nowDate,thisSetInfo);
				entity.setIsShow(isShow);//当前数据是否展示在表单上（0否，1是）
			}

			//完成
			res = tpShopRegisterPhaseRecordMapper.update(entity);
			
			// 结算学分奖励
			if (thisSetInfo.getParentId() == -1) {
				settlePointReward(entity.getId());
			}
		}else {
			//点击完成时，阶段设置被删除的情况
			res = -1;
		}

		return res;
	}

	/**
	 * 递归完成父节点
	 * @param operateCompanyId 当前的运营公司
	 * @param recordInfoByCompanyIdList 跟踪单当前公司所有数据
	 * @param setList 所有的阶段设置信息
	 * @param nowDate 当前时间
	 * @param thisSetInfo 当前的设置信息
	 * @return
	 */
	public int addParentsRecord(Long operateCompanyId,List<TpShopRegisterPhaseRecord> recordInfoByCompanyIdList,List<TpShopRegisterPhaseSet> setList,Date nowDate,TpShopRegisterPhaseSet thisSetInfo){
		int isShow = 0;
		//判断当前任务是否是分支流程中的最后一个分支任务，是的话父节点的数据也要修改成完成状态，进入下一个阶段
		List<TpShopRegisterPhaseRecord> pList = recordInfoByCompanyIdList.stream()
				.filter(item->
						item.getParentId().equals(thisSetInfo.getParentId())
								&& ((item.getEndUser()!=null && !item.getEndUser().equals(""))
								|| item.getSetId().equals(thisSetInfo.getId()))
				).collect(Collectors.toList());

		List<TpShopRegisterPhaseSet> isLastSet = setList.stream()
				.filter(item->item.getParentId().equals(thisSetInfo.getParentId()))//先获取同属于该父id底下的设置信息
				.filter(item->{//再过滤没有完成的任务信息
					boolean hasOtherSet = true;
					for(TpShopRegisterPhaseRecord recordItem : pList ){
						if(recordItem.getSetId().equals(item.getId())){
							hasOtherSet = false;
							break;
						}
					}
					return hasOtherSet;
				})
				.collect(Collectors.toList());


		//是最后一个分支任务
		if(!(isLastSet!=null && isLastSet.size()>0)){
		//if(!(pList!=null && pList.size()>0)){
			//父节点的数据修改成完成状态
			//获取父节点设置数据
			List<TpShopRegisterPhaseSet> parentSet = setList.stream().filter(item->item.getId().equals(thisSetInfo.getParentId())).collect(Collectors.toList());
			//获取父节点跟踪单数据
			List<TpShopRegisterPhaseRecord> parentRecordInfo = recordInfoByCompanyIdList.stream().filter(item->item.getSetId().equals(thisSetInfo.getParentId())).collect(Collectors.toList());

			if(parentSet!=null && parentSet.size()>0 && parentRecordInfo!=null && parentRecordInfo.size()>0){
				//初始化参数
				TpShopRegisterPhaseRecord entityEdie = new TpShopRegisterPhaseRecord();
				entityEdie.setId(parentRecordInfo.get(0).getId());
				//填入修改的参数
				entityEdie = editEntitySet(entityEdie,parentRecordInfo.get(0),parentSet.get(0),nowDate);
				//修改父节点数据
				tpShopRegisterPhaseRecordMapper.update(entityEdie);
				//再递归判断父节点是否是分支流程中的最后一个分支任务，直到返回进入下一阶段的父节点
				isShow = addParentsRecord(operateCompanyId,recordInfoByCompanyIdList,setList,nowDate,parentSet.get(0));

			}else {//非正常情况，无法继续
				isShow = 1;//当前数据是否展示在表单上（0否，1是）
			}

		}else {//不是最后一个分支任务,则新增下一个阶段任务，完成当前任务
			List<TpShopRegisterPhaseRecord> thisEntityList = recordInfoByCompanyIdList.stream()
					.filter(item->item.getSetId().equals(thisSetInfo.getId())).collect(Collectors.toList());

			if(thisEntityList!=null && thisEntityList.size()>0){
				if(thisSetInfo.getSetType()!=2){//如果不是分支类型,新增下一阶段的跟踪信息,否则不新增下一条，因为分支集合的一定早就有了
					TpShopRegisterPhaseRecord thisEntity = thisEntityList.get(0);
					//新增下一阶段的跟踪信息
					isShow = addNextRecord(thisEntity,setList,nowDate);
				}
				//完成当前任务
				List<TpShopRegisterPhaseRecord> nowRecordList = recordInfoByCompanyIdList.stream()
						.filter( item-> item.getSetId().equals(thisSetInfo.getId()) && item.getOperateCompanyId().equals(operateCompanyId) )
						.collect(Collectors.toList());
				//初始化参数
				TpShopRegisterPhaseRecord entityEdie = new TpShopRegisterPhaseRecord();
				entityEdie.setId(nowRecordList.get(0).getId());
				//填入修改的参数
				entityEdie = editEntitySet(entityEdie,nowRecordList.get(0),thisSetInfo,nowDate);
				//修改节点数据
				tpShopRegisterPhaseRecordMapper.update(entityEdie);

			}else {
				isShow = 1;//当前数据是否展示在表单上（0否，1是）
			}
		}
		return isShow;
	}

	/**
	 * 新增下一阶段的跟踪信息
	 * @param thisEntity 当前的跟踪单参数
	 * @param setList 所有的设置信息
	 * @param nowDate 当前时间
	 * @return
	 */
	public int addNextRecord(TpShopRegisterPhaseRecord thisEntity,List<TpShopRegisterPhaseSet> setList,Date nowDate){
		int isShow = 0;
		int nextNum =  thisEntity.getPhaseNum() +1;
		List<TpShopRegisterPhaseSet> nestSetInfoList = setList.stream()
				.filter(item-> item.getPhaseNum().equals(nextNum) && item.getParentId().equals(thisEntity.getParentId())).collect(Collectors.toList());
		//查看是否有下一个阶段，有的话新增一条，没有的话将刚刚完成的那一条设置成显示状态（最终阶段一定是一个主流程，不可能是分支流程）
		if(nestSetInfoList!=null && nestSetInfoList.size()>0){//有下一个阶段
			//新增跟踪单
			isShow = addRecord(nestSetInfoList,thisEntity.getOperateCompanyId(),nowDate,setList);
		}else {//没有的话将刚刚完成的那一条设置成显示状态（最终阶段一定是一个主流程，不可能是分支流程）
			isShow = 1;//当前数据是否展示在表单上（0否，1是）
		}
		return isShow;
	}

	/**
	 * 新增跟踪单
	 * @param nestSetInfoList 新增的跟踪单对应的阶段设置信息
	 * @param perateCompanyId 运营公司id
	 * @param nowDate 当前时间
	 * @param setList 所有是阶段设置信息
	 * @return
	 */
	public int addRecord(List<TpShopRegisterPhaseSet> nestSetInfoList,Long perateCompanyId,Date nowDate,List<TpShopRegisterPhaseSet> setList){
		int isShow = 0;
		TpShopRegisterPhaseSet nextSet =nestSetInfoList.get(0);
		//填入新增的参数
		TpShopRegisterPhaseRecord entityAdd = addEntitySet(perateCompanyId,nowDate,nextSet);
		if(nextSet.getSetType()!=0){//1分支集合,2任务分支
			//查询下一个阶段是否有子流程，没有则将刚刚完成的那一条设置成显示状态
			List<TpShopRegisterPhaseSet> hasSonSet = setList.stream()
					.filter(item->item.getParentId().equals(nextSet.getId()))
					.sorted(Comparator.comparing(TpShopRegisterPhaseSet::getPhaseNum))//按阶段顺序排序
					.collect(Collectors.toList());
			if( hasSonSet!=null && hasSonSet.size()>0 ){//若有子流程，则递归新增子流程，直到该节点是任务类型为止
				if(hasSonSet.get(0).getSetType()!=0){//若子流程还不是任务类型，则递归新增子流程
					if(hasSonSet.get(0).getSetType()==1){//分支集合
						//新增信息填入
						TpShopRegisterPhaseRecord entityAddSon = addEntitySet(perateCompanyId,nowDate,hasSonSet.get(0));
						tpShopRegisterPhaseRecordMapper.insert(entityAddSon);//新增
						//递归新增子流程
						addChildrensRecord(perateCompanyId, nowDate,setList,hasSonSet.get(0).getId());
					}else {//如果是任务分支，因为是并列的，所以每个分支都需要新增
						hasSonSet.forEach(item->{
							//新增信息填入
							TpShopRegisterPhaseRecord entityAddSon = addEntitySet(perateCompanyId,nowDate,item);
							tpShopRegisterPhaseRecordMapper.insert(entityAddSon);//新增
							//递归新增子流程
							addChildrensRecord(perateCompanyId, nowDate,setList,item.getId());
						});
					}
				}else {
					//新增信息填入
					TpShopRegisterPhaseRecord entityAddSon = addEntitySet(perateCompanyId,nowDate,hasSonSet.get(0));
					tpShopRegisterPhaseRecordMapper.insert(entityAddSon);//新增
				}
			}else {//无子流程，则不新增下一条，将刚刚完成的那一条设置成显示状态
				isShow = 1;//当前数据是否展示在表单上（0否，1是）
				//res = -2;
			}
			tpShopRegisterPhaseRecordMapper.insert(entityAdd);
		}else {//如果是阶段任务，直接新增
			tpShopRegisterPhaseRecordMapper.insert(entityAdd);
		}
		return isShow;
	}




	/**
	 * 递归查询子类数据,新增
	 * @param operateCompanyId 运营公司id
	 * @param nowDate 当前时间
	 * @param setList 设置信息
	 * @param nextId 下一级id
	 */
	public void addChildrensRecord(Long operateCompanyId,Date nowDate,List<TpShopRegisterPhaseSet> setList,Long nextId){
		//查询下一个阶段是否有子流程
		List<TpShopRegisterPhaseSet> hasSonSet = setList.stream()
				.filter(item->item.getParentId().equals(nextId))
				.sorted(Comparator.comparing(TpShopRegisterPhaseSet::getPhaseNum))//按阶段顺序排序
				.collect(Collectors.toList());
		if( hasSonSet!=null && hasSonSet.size()>0 ){//若有子流程，则递归新增子流程，直到该节点是任务类型为止
			if(hasSonSet.get(0).getSetType()!=0){//若子流程还不是任务类型，则递归新增子流程
				if(hasSonSet.get(0).getSetType()==1){//分支集合
					//新增信息填入
					TpShopRegisterPhaseRecord entityAddSon = addEntitySet(operateCompanyId,nowDate,hasSonSet.get(0));
					//新增
					tpShopRegisterPhaseRecordMapper.insert(entityAddSon);
					//递归新增子流程
					addChildrensRecord(operateCompanyId, nowDate,setList,hasSonSet.get(0).getId());
				}else {//如果是任务分支，因为是并列的，所以每个分支都需要新增
					hasSonSet.forEach(item->{
						//新增信息填入
						TpShopRegisterPhaseRecord entityAddSon = addEntitySet(operateCompanyId,nowDate,item);
						//新增
						tpShopRegisterPhaseRecordMapper.insert(entityAddSon);
						//递归新增子流程
						addChildrensRecord(operateCompanyId, nowDate,setList,item.getId());
					});
				}
			}else {
				//新增信息填入
				TpShopRegisterPhaseRecord entityAddSon = addEntitySet(operateCompanyId,nowDate,hasSonSet.get(0));
				//新增
				tpShopRegisterPhaseRecordMapper.insert(entityAddSon);
			}

		}
	}


	/**
	 * 填入修改（完成）的参数
	 * @param entity 填入并需要返回的参数
	 * @param recordInfo 当前需要完成的跟踪单记录信息
	 * @param setInfo 当前跟踪单对应的设置信息
	 * @param nowDate 当前时间
	 * @return
	 */
	public TpShopRegisterPhaseRecord editEntitySet(TpShopRegisterPhaseRecord entity,TpShopRegisterPhaseRecord recordInfo,TpShopRegisterPhaseSet setInfo,Date nowDate){
		//********运营公司id********
		entity.setOperateCompanyId(recordInfo.getOperateCompanyId());
		//********状态********
		entity.setStatus(1);
		//********阶段********
		entity.setPhaseNum(setInfo.getPhaseNum());

		if(recordInfo.getSetType()==0){//只有阶段任务才有这些信息
			//********时效********
			BigDecimal decimal =setInfo.getWorkTime();
			Integer workTime = decimal.intValue();
			entity.setWorkTime(decimal);
			//********阶段实际完成时间********
			entity.setRealityEndTime(nowDate);
			//********阶段预计完成时间********
			Date thatDate = countEndTimeSkipWorkDate(recordInfo.getStartTime(),workTime,1);
			entity.setPlanEndTime(thatDate);
			//计算假期时间
			//********工作时间********
			int dsyNum = checkOverTime(recordInfo.getStartTime(),nowDate,1);
			entity.setRealityWorkTime(BigDecimal.valueOf(dsyNum));
			//********超时时间********
			int overTime = 0;
			int overNum = dsyNum - workTime;//工作时间减时效时间
			if(overNum>0){
				overTime = overNum;
			}
			entity.setOverTime(BigDecimal.valueOf(overTime));
			//********负责人Id********
			entity.setHeadUserId(setInfo.getHeadUserId()==null?"":setInfo.getHeadUserId());
			//********完成的顺序********
			//获取记录表信息
			Map<String,Object> maxRecordInfo = new TpShopRegisterPhaseRecord()
					.addField("B.EndSort AS sortNum")
					.addLeftJoin("( SELECT MAX ( EndSort ) AS EndSort, OperateCompanyId FROM TP_ShopRegisterPhaseRecord GROUP BY OperateCompanyId ) B ON B.OperateCompanyId = A.OperateCompanyId")
					.where("A.Id = " + recordInfo.getId())
					.where("A.SetType = 0 ")
					.queryFirstMap();
			entity.setEndSort(Integer.parseInt((maxRecordInfo.get("sortNum")==null? "0" : maxRecordInfo.get("sortNum").toString()))+1);
		}

		//********阶段名称********
		entity.setPhaseName(setInfo.getPhaseName());
		//********设置类型（0阶段任务，1分支集合，2任务分支）********
		entity.setSetType(setInfo.getSetType());
		//********TP_ShopRegisterPhaseSet表id（统计用，set表可能被删除）********
		entity.setSetId(setInfo.getId());
		//********TP_ShopRegisterPhaseSet表父id（set表可能被删除）********
		entity.setParentId(setInfo.getParentId());
		//********流程类型（0主流程，1分支流程）********
		entity.setPhaseType(setInfo.getPhaseType());
		//********所有的TP_ShopRegisterPhaseSet表父节点（不包含自身节点，多个用,隔开）********
		entity.setParentNode(setInfo.getParentNode());
		//********完成该任务的用户********
		entity.setEndUser(ShiroUtils.getUserId());

		//********当前数据是否展示在表单上（0否，1是）********
		entity.setIsShow(0);
		return entity;
	}


	/**
	 * 填入新增参数
	 * @param operateCompanyId 运营公司id
	 * @param nowDate 当前时间
	 * @param setInfo 阶段设置
	 * @return
	 */
	public TpShopRegisterPhaseRecord addEntitySet(Long operateCompanyId,Date nowDate,TpShopRegisterPhaseSet setInfo){
		TpShopRegisterPhaseRecord entityAdd = new TpShopRegisterPhaseRecord();
		entityAdd.setStatus(1);//状态
		entityAdd.setOperateCompanyId(operateCompanyId);//运营公司id
		entityAdd.setPhaseNum(setInfo.getPhaseNum());//阶段顺序
		entityAdd.setStartTime(nowDate);//阶段开始时间
		entityAdd.setSetType(setInfo.getSetType());//设置类型（0阶段任务，1分支集合，2任务分支）
		entityAdd.setSetId(setInfo.getId());//TP_ShopRegisterPhaseSet表id（统计用，set表可能被删除）
		entityAdd.setPhaseType(setInfo.getPhaseType());//流程类型（0主流程，1分支流程）
		entityAdd.setParentId(setInfo.getParentId());//父id
		int isShow = (setInfo.getSetType()!=0?0:1);//是否显示，若是1分支集合或2任务分支则不显示
		entityAdd.setIsShow(isShow);//是否显示
		return entityAdd;
	}



	/**
	 * 删除
	 * @operateCompanyId operateCompanyId
	 * @return
	 */
	@Override
	public void deleteTpShopRegisterPhaseRecord(Long operateCompanyId) {
		diySqlMapper.deleteTpShopRegisterPhaseRecord(operateCompanyId);
	}

	/**
	 * 设置店铺
	 * @param params
	 * @return
	 */
	@Override
	public int setShopOrContent(Map<String, Object> params){
		TpShopRegisterPhaseRecord entity = JSON.parseObject(JSON.toJSONString(params), TpShopRegisterPhaseRecord.class);
		entity.setStatus(1);
		return tpShopRegisterPhaseRecordMapper.update(entity);
	}



	public int checkOverTime(Date start, Date end, int beginNum){

		//获取假期设置数据
		List<TpHolidaySet> tpHolidaySetList = new TpHolidaySet()
				.queryList();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		int overTime = 0;//累计时间
		try {
			start = sdf.parse(sdf.format(start));
			end = sdf.parse(sdf.format(end));
		} catch (ParseException e) {
			e.printStackTrace();
		}
		long startTime = start.getTime();
		long endTime = end.getTime();
		long betweenDays = (endTime - startTime) / (1000 * 3600 * 24);
		//开始时间和结束时间相差的天数
		int dsyNum = Integer.parseInt(String.valueOf(betweenDays));
		if(dsyNum>0){//大于一天的时候才计算超时时间

			//计算超时时间
			Calendar calendar = null;
			//j=1,制单当天不算时效
			for(int j=beginNum;j<=dsyNum;j++){
				calendar=Calendar.getInstance();
				calendar.setTime(start);
				calendar.add(Calendar.DAY_OF_MONTH, +j);
				Date thatDate = calendar.getTime();
				String thatDay = sdf.format(thatDate);
				//判断该日是否是休息日
				boolean hasSetHoliDay = false;//标识该日是否设置
				if(tpHolidaySetList!=null && tpHolidaySetList.size()>0){
					for (int h=0;h<tpHolidaySetList.size();h++){
						String holiday = sdf.format(tpHolidaySetList.get(h).getSetDate());
						if(thatDay.equals(holiday)){
							hasSetHoliDay = true;
							if(tpHolidaySetList.get(h).getIsHoliday()==0){//假期
								//overTime --;
							}else {//工作日
								overTime ++;
							}
							break;
						}
					}
				}
				//若没有被设置，则再判断该天是周末还是工作日
				if(!hasSetHoliDay){
					String[] weeks = {"7","1","2","3","4","5","6"};
					Calendar cal1 = Calendar.getInstance();
					cal1.setTime(thatDate);
					int week_index = cal1.get(Calendar.DAY_OF_WEEK) - 1;
					if(week_index<0){
						week_index = 0;
					}
					String weekNum = weeks[week_index];
					if(weekNum.equals("7") || weekNum.equals("6")){
						//overTime --;
					}else {//工作日
						overTime ++;
					}
				}
			}
		}
		return overTime;
	}


	public Date countEndTimeSkipWorkDate(Date start,int workDay, int beginNum){
		//获取假期设置数据
		List<TpHolidaySet> tpHolidaySetList = new TpHolidaySet()
				.queryList();

		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

		int workDayCount = 0;//存放计算过的时效
		int allDay = 0;//存放总共的时间
		Calendar calendar = null;
		for(int i=beginNum;;i++){
			calendar=Calendar.getInstance();
			calendar.setTime(start);
			calendar.add(Calendar.DAY_OF_MONTH, +i);
			Date thatDate = calendar.getTime();
			String thatDay = sdf.format(thatDate);

			//判断该日是否是休息日
			boolean hasSetHoliDay = false;//标识该日是否设置
			if(tpHolidaySetList!=null && tpHolidaySetList.size()>0){
				for (int h=0;h<tpHolidaySetList.size();h++){
					String holiday = sdf.format(tpHolidaySetList.get(h).getSetDate());
					if(thatDay.equals(holiday)){
						hasSetHoliDay = true;
						if(tpHolidaySetList.get(h).getIsHoliday()==1){//工作日
							workDayCount++;
						}//假期不做操作
						break;
					}
				}
			}

			//若没有被设置，则再判断该天是周末还是工作日
			if(!hasSetHoliDay){
				String[] weeks = {"7","1","2","3","4","5","6"};
				Calendar cal1 = Calendar.getInstance();
				cal1.setTime(thatDate);
				int week_index = cal1.get(Calendar.DAY_OF_WEEK) - 1;
				if(week_index<0){
					week_index = 0;
				}
				String weekNum = weeks[week_index];
				if(weekNum.equals("7") || weekNum.equals("6")){

				}else {//工作日
					workDayCount ++;
				}
			}

			allDay = i;
			if(workDayCount>=workDay)break;//跳出循环
		}

		calendar=Calendar.getInstance();
		calendar.setTime(start);
		calendar.add(Calendar.DAY_OF_MONTH, +allDay);//开始时间 + （工作天数、假期天数）
		Date endDateTime = calendar.getTime();

		return endDateTime;
	}

	@Override
	public void settlePointReward(Long id) throws Exception {
		TpShopRegisterPhaseRecord entity = new TpShopRegisterPhaseRecord()
				.setId(id)
				.queryFirst();
		TpShopRegisterPhaseSet setInfo = new TpShopRegisterPhaseSet().setId(entity.getSetId()).queryFirst();
		ThrOperateCompanyApply company = new ThrOperateCompanyApply().setId(entity.getOperateCompanyId()).queryFirst();
		{
        	String itemName = "学堂考核";
        	String itemNameSub = "新手任务";
        	Integer type = TcwUserPointRunningEnum.Type.SHOP_REGIST_REWARD.value;
			Long relativeId = entity.getId();
			BigDecimal pointChange = setInfo.getPoint().negate();
			String remark = company.getVgsjc() + setInfo.getPhaseName() + "完成";
			tcwAccountCountForUserService.changePoint_JIAO_WU_CHU(itemName, itemNameSub, type, relativeId, pointChange, remark);
		}
		{
			TsUserChange tsUserChange = new TsUserChange().setId(company.getOperatorChangeId()).queryFirst();
        	String item = "学堂考核";
        	String itemSub = "新手任务";
        	Integer type = TcwUserPointRunningEnum.Type.SHOP_REGIST_REWARD.value;
			Long relativeId = entity.getId();
            String userId = tsUserChange.getUserId();
            String userName = tsUserChange.getUserName();
            BigDecimal pointChange = setInfo.getPoint();
            String remark = company.getVgsjc() + setInfo.getPhaseName() + "完成";
			ChangePointDto changePointDto = new ChangePointDto(item, itemSub, type, relativeId, userId, userName, pointChange, remark);
			ChangePointFrozenDto changePointFrozenDto = null;
			tcwAccountCountForUserService.change(changePointDto, changePointFrozenDto);
		}
	}



	/* 这里是未扣除假期设置的时间计算
			Calendar calendar= Calendar.getInstance();
			calendar.setTime(recordInfo.getStartTime());//开始时间
			calendar.add(Calendar.DAY_OF_MONTH, +allDay);//开始时间 + 时效的天数
			Date thatDate = calendar.getTime();
			entity.setPlanEndTime(thatDate);
			//工作时间
			int dsyNum = 0;
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			try {
				Date start = sdf.parse(sdf.format(recordInfo.getStartTime()));
				Date end = sdf.parse(sdf.format(nowDate));
				long startTime = start.getTime();
				long endTime = end.getTime();
				long betweenDays = (endTime - startTime) / (1000 * 3600 * 24);
				//开始时间和结束时间相差的天数
				dsyNum = Integer.parseInt(String.valueOf(betweenDays));
			} catch (ParseException e) {
				e.printStackTrace();
			}
			 */
}
